﻿using Engine;
using Engine.Graphics;
using Game;
using GameEntitySystem;
using System.Collections.Generic;
using TemplatesDatabase;

namespace SAGhoul.Tartareosity
{
	public class SubsystemPortals : Subsystem, IDrawable
	{
		public static Color Color => Color.White;// new(125, 130, 155);
		public SubsystemSky m_subsystemSky;
		public Dictionary<Point3, Portal>.ValueCollection Portals => m_portals.Values;
		public int[] DrawOrders => [110];

		readonly PrimitivesRenderer3D m_primitivesRenderer = new();
		readonly Dictionary<Point3, Portal> m_portals = [];

		public void AddPortal(Point3 point3, Portal portal)
		{
			m_portals.TryAdd(point3, portal);
		}
		public void Draw(Camera camera, int drawOrder)
		{
			var batch = m_primitivesRenderer.TexturedBatch(SAGhoulsManager.AnimateTextureByTime, false, 0, DepthStencilState.DepthRead, RasterizerState.CullCounterClockwiseScissor, BlendState.AlphaBlend, SamplerState.LinearClamp);
			foreach (Portal portal in Portals)
			{
				Vector3 size = portal.Max - portal.Min;
				Vector3 center = (portal.Min + portal.Max) / 2f;
				Vector3 vector = center - camera.ViewPosition;
				Vector3 min = new(portal.Min.X, portal.Max.Y, portal.Min.Z);
				float num = Vector3.Dot(vector, camera.ViewDirection);
				if (num > 0.01f)
				{
					float num2 = vector.Length();
					if (num2 < m_subsystemSky.VisibilityRange)
					{
						Vector3 v = (0f - (0.01f + 0.02f * num)) / num2 * vector;
						Color color = Color.LerpNotSaturated(
							Color,
							m_subsystemSky.ViewFogColor,
							m_subsystemSky.CalculateFog(camera.ViewPosition, center)
						);
						batch.QueueQuad(min, min + new Vector3(size.X, 0f, 0f), portal.Max, min + new Vector3(0f, 0f, size.Z),
							new Vector2(0f, 0f), new Vector2(1f, 0f), new Vector2(1f, 1f), new Vector2(0f, 1f), color);
					}
				}
			}
			m_primitivesRenderer.Flush(camera.ViewProjectionMatrix);
		}

		public override void Load(ValuesDictionary valuesDictionary)
		{
			m_subsystemSky = Project.FindSubsystem<SubsystemSky>(true);
		}
	}
}
